﻿using LD.Model;
using MiniExcelLibs;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace LD
{
    public class ExcelHelper
    {
        public static void Save(string fileName, List<ScrewDataModel> data)
        {
            if (data == null)
                return;
            string filePath = Path.Combine(Appbus.BasePath, "电批原始数据\\" + DateTime.Now.ToString("yyyy-MM-dd"));
            if (!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);

            MiniExcel.SaveAs(Path.Combine(filePath, $"{fileName}.csv"), data);
        }
        public static void Save(TB_Alarm alarm)
        {
            if (alarm == null)
                return;
            string filePath = Path.Combine(Appbus.BasePath, "报警信息");
            if (!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);

            MiniExcel.SaveAs(Path.Combine(filePath, $"{DateTime.Now.ToString("yyyy-MM-dd")}.csv"), alarm);
        }
        /// <summary>
        /// 保存WIP数据
        /// </summary>
        /// <param name="wip"></param>
        public static void Save(TB_WIP wip,int type=1)
        {
            if (wip == null)
                return;
            string filePath = Path.Combine(Appbus.BasePath, "生产数据");
            if (!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);
            var _wip = new object[]{ };
            string excel_name = "";
            if (type == 1)
            {
                //wip信息保存
                excel_name = Path.Combine(filePath, $"Wip信息_{DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss")}.csv");
                _wip = new[]
                {
                    new {
                        NG率=wip.NgYield,
                        良率=wip.PassYield,
                        生产总量=wip.All,
                        真空报警率=wip.vacAlRate,
                        抛料率 = wip.PaoLiaoYield,
                        螺丝总量=wip.Screw_Total,
                    }
                };
            }
            else if(type == 2)
            {
                //真空数据保存
                excel_name = Path.Combine(filePath, $"_VacAlarmSummer_{DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss")}.csv");
                _wip = new[]
                  {
                    new {
                        Date=DateTime.Now,
                        Line = Cache.GetCache(CONST.Line),
                        FixtureName=Cache.GetCache(CONST.FixtureName),
                        Alarm_Units=wip.vacAlNum,
                        Total_Units=wip.All,
                        Percentage=wip.vacAlRate
                    }
                };
            }else if (type == 3)
            {
                //抛料信息保存
                excel_name = Path.Combine(filePath, $"_SuckSpit_{DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss")}.csv");
                _wip = new[]
                {
                    new
                    {
                        Line = Cache.GetCache(CONST.Line),
                        FixtureName=Cache.GetCache(CONST.FixtureName),
                        抛料数量 = wip.Screw_Paoliao,
                        螺丝总数量 = wip.Screw_Total,
                        抛料率 = wip.PaoLiaoYield,
                    }
                };  
            }
            MiniExcel.SaveAs(Path.Combine(filePath, excel_name), _wip);
        }
        public static void Save(TB_Product product)
        {
            if (product == null)
                return;
            string filePath = Path.Combine(Appbus.BasePath, "扭力反馈数据");
            if (!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);

            AddHeard(filePath);

            ScrewDataParse(product, filePath);
        }
        public static void ScrewDataParse(TB_Product product, string filePath)
        {
            //var product = DBHelper.Instance.Sql.Queryable<TB_Product>()
            //                    .Includes(x => x.ScrewDatas)
            //                    .Where(x => x.Pid == pid)
            //                    .First();
            if (product != null)
            {
                product.Result = product.ScrewDatas.Where(p => p.Result == "FAIL").Count() > 0 ? "FAIL" : "PASS";
                product.CCD_Result = product.ScrewDatas.Where(p => p.CCD_Result == "NG").Count() > 0 ? "NG" : "OK";
                product.Torque_Result = product.ScrewDatas.Where(p => p.Torque_Result == "NG").Count() > 0 ? "NG" : "OK";
                product.Angle_Result = product.ScrewDatas.Where(p => p.Angle_Result == "NG").Count() > 0 ? "NG" : "OK";
                product.Accumulative_Result = product.ScrewDatas.Where(p => p.Accumulative_Result == "NG").Count() > 0 ? "NG" : "OK";
                product.VacAlarm = product.ScrewDatas.Sum(p => p.Vac_alarm);
                product.TossingScrew = product.ScrewDatas.Sum(p => p.Tossing_screw);

                StringBuilder sb = new StringBuilder();
                sb.Append(product.Barcode + ",");
                sb.Append(product.Config + ",");
                sb.Append(product.Group + ",");
                sb.Append(product.StartTime.ToShortDateString() + ",");
                sb.Append(product.StartTime.ToShortTimeString() + ",");
                sb.Append(product.FixtureName + ",");
                sb.Append(product.CycleTime + ",");
                sb.Append(product.Result + ",");
                sb.Append(product.CCD_Result + ",");
                sb.Append(product.Torque_Result + ",");
                sb.Append(product.Angle_Result + ",");
                sb.Append(product.Accumulative_Result + ",");

                for (int i = 1; i <= Appbus.Screw_Qty; i++)
                {
                    var find = product.ScrewDatas.Where(p => p.Location == i + "").FirstOrDefault();
                    if (find != null)
                    {
                        sb.Append($"{i},");
                        sb.Append($"{find.Angle},");
                        sb.Append($"{find.Target_Torque},");
                        sb.Append($"{find.Actual_Torque},");
                        sb.Append($"{find.ProductHole_X},");
                        sb.Append($"{find.ProductHole_Y},");
                        sb.Append($"{find.ScrewHole_X},");
                        sb.Append($"{find.ScrewHole_Y},");
                        sb.Append($"{find.Productoffset_X},");
                        sb.Append($"{find.Productoffset_Y},");

                        product.NgReason += find.Remark;
                        product.NgScrewNo += find.Accumulative_Result == "NG" ? $"{find.Location};" : "";
                    }
                    else
                    {
                        sb.Append(",");
                        sb.Append(",");
                        sb.Append(",");
                        sb.Append(",");
                        sb.Append(",");
                        sb.Append(",");
                        sb.Append(",");
                        sb.Append(",");
                        sb.Append(",");
                        sb.Append(",");
                    }
                }

                sb.Append(product.NgReason + ",");
                sb.Append(product.NgScrewNo + ",");
                sb.Append(product.VacAlarm + ",");
                sb.Append(product.TossingScrew + "\n");

                File.AppendAllText(Path.Combine(filePath, $"{DateTime.Now.ToString("yyyy-MM-dd")}.csv"), sb.ToString());
                DBHelper.Instance.Sql.Updateable(product).ExecuteCommand();
            }
        }
        public static void AddHeard(string filePath)
        {
            if (!File.Exists(Path.Combine(filePath, $"{DateTime.Now.ToString("yyyy-MM-dd")}.csv")))
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("SerialNumber,");
                sb.Append("Config,");
                sb.Append("Group,");
                sb.Append("Date,");
                sb.Append("Time,");
                sb.Append("FixtureName,");
                sb.Append("CycleTime,");
                sb.Append("Result,");
                sb.Append("CCD_Result,");
                sb.Append("Torque_Result,");
                sb.Append("Angle_Result,");
                sb.Append("Accumulative_Result,");

                for (int i = 1; i <= Appbus.Screw_Qty; i++)
                {
                    sb.Append("Location,");
                    sb.Append("Angle,");
                    sb.Append("Target_Torque,");
                    sb.Append("Actual_Torque,");
                    sb.Append($"ProductHole_{i}X,");
                    sb.Append($"ProductHole_{i}Y,");
                    sb.Append($"ScrewHole_L{i}X,");
                    sb.Append($"ScrewHole_L{i}Y,");
                    sb.Append($"Productoffset_{i}X,");
                    sb.Append($"Productoffset_{i}Y,");
                }

                //sb.Append("Location,");
                //sb.Append("Angle,");
                //sb.Append("Target_Torque,");
                //sb.Append("Actual_Torque,");
                //sb.Append("ProductHole_2X,");
                //sb.Append("ProductHole_2Y,");
                //sb.Append("ScrewHole_L2X,");
                //sb.Append("ScrewHole_L2Y,");
                //sb.Append("Productoffset_2X,");
                //sb.Append("Productoffset_2Y,");

                sb.Append("NGReason,");
                sb.Append("NGScrewNO,");
                sb.Append("Vac alarm,");
                sb.Append("Tossing screw" + "\n");

                File.AppendAllText(Path.Combine(filePath, $"{DateTime.Now.ToString("yyyy-MM-dd")}.csv"), sb.ToString());
            }
        }
    }
}
